import 'package:flutter/material.dart';
import 'package:xws/models/goods/pub_obj.dart';
import 'package:xws/models/loc_obj.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/qiniu_oss.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/utils/loc_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/goods_config/add_addr.dart';
import 'package:xws/widgets/goods_config/add_record.dart';
import 'package:xws/widgets/goods_config/des_box.dart';
import 'package:xws/widgets/goods_config/select_imgs_video.dart';
import 'package:xws/widgets/goods_config/select_quality.dart';
import 'package:xws/widgets/goods_config/set_count.dart';
import 'package:xws/widgets/goods_config/set_price.dart';
import 'package:xws/widgets/safe_scaffold.dart';

/// 发布物品
class PubPage extends StatelessWidget {
  const PubPage({Key? key, required this.pubObj}) : super(key: key);

  final PubObj pubObj;

  /// 发布
  Future<void> _post(BuildContext context) async {
    final String check = pubObj.check();

    if (check != 'success') {
      ct(check);
      return;
    }

    loading(context);

    final bool p = await getPermission(Permission.locationWhenInUse);
    if (!p) {
      ct('获取位置信息失败');
      close(context);
      return;
    }
    final LocObj? loc = await getLocation();
    pubObj.setLocation(loc);

    bool uploadRes = await _uploadImgs();
    uploadRes = uploadRes && await _uploadRecord();
    uploadRes = uploadRes && await _uploadVideo();

    if (!uploadRes) {
      close(context);
      return;
    }

    final bool r = await publishGoods(pubObj);
    close(context);

    if (r) pop(context, value: true);
  }

  /// 上传图片
  Future<bool> _uploadImgs() async {
    if (pubObj.photoUrlList.first.startsWith('http')) return true;

    final List<String> r = await QiniuOSS.uploadFiles(
      pubObj.photoUrlList,
      Dir.goods,
    );

    if (r.length != pubObj.photoUrlList.length) {
      et('图片上传未成功');
      return false;
    }

    pubObj.photoUrlList = r;

    return true;
  }

  /// 上传录音
  Future<bool> _uploadRecord() async {
    if (pubObj.recordUrl == null || pubObj.recordUrl!.startsWith('http')) return true;

    final List<String> r = await QiniuOSS.uploadFiles(
      <String>[pubObj.recordUrl!],
      Dir.goods,
    );

    if (r.isEmpty) {
      et('录音上传未成功');
      return false;
    }

    pubObj.recordUrl = r.single;

    return true;
  }

  /// 上传视频
  Future<bool> _uploadVideo() async {
    if (pubObj.videoUrl == null || pubObj.videoUrl!.startsWith('http')) return true;

    final List<String> r = await QiniuOSS.uploadFiles(
      <String>[pubObj.videoUrl!],
      Dir.goods,
    );

    if (r.isEmpty) return false;

    pubObj.videoUrl = r.single;

    return true;
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      tapToCloseKeyboard: true,
      backgroundColor: white(context),
      titleText: '发布好物',
      actions: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 10),
          child: AppBtn(onTap: () => _post(context), text: '发布'),
        ),
      ],
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            DesBox(
              initialValue: pubObj.description,
              onChanged: (String v) => pubObj.description = v,
            ),
            AddRecord(
              initInd: pubObj.recordInd,
              initPath: pubObj.recordUrl,
              onPathChanged: (String? v) => pubObj.recordUrl = v,
              onRecoedIndChange: (double? ind) => pubObj.recordInd = ind,
            ),
            _spacer,
            SelectImagesVideo(
              initImages: pubObj.photoUrlList,
              initVideoPath: pubObj.videoUrl,
              onImgChanged: (List<String> v) => pubObj.photoUrlList = v,
              onVideoChanged: (String? v) => pubObj.videoUrl = v,
            ),
            _spacer,
            SelectQuality(
              initSelect: pubObj.age,
              onSelected: (String? v) => pubObj.age = v,
            ),
            _spacer,
            AddAddr(
              initValue: pubObj.reg,
              onCoordinateChanged: (LocObj? loc) => pubObj.setLocation(loc),
            ),
            _spacer,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                SetPrice(
                  init: pubObj.originalPrice,
                  onChanged: (double? p) => pubObj.originalPrice = p,
                ),
                SetCount(
                  init: pubObj.count,
                  onChanged: (int v) => pubObj.count = v,
                ),
              ],
            ),
            const SizedBox(height: 100),
          ],
        ),
      ),
    );
  }

  /// 间隔
  Widget get _spacer => const SizedBox(height: 16);
}
